﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Catering.View_Operaction;
using System.Text;
using System.Collections;

namespace Catering.Catering_Page.Kufang
{
    public partial class ImportExcel : System.Web.UI.Page
    {
        public string strBgC = "background-color: #f4fbff; height: 32px";
        DataBase_Manage_Operaction dmo = new DataBase_Manage_Operaction();
        Catering.View_Operaction_Common voc = new View_Operaction_Common();
        protected void Page_Load(object sender, EventArgs e)
        {
            this.txt_addtime.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy/MM/dd',maxDate:'%y-%M-%d'})");
            if (!IsPostBack)
            {
                string groupid = "";
                string classid = "";
                if (Request.QueryString["GroupID"] != null) groupid = Request.QueryString["GroupID"].ToString();
                if (Request.QueryString["ClassID"] != null) classid = Request.QueryString["ClassID"].ToString();
                this.HFGroupID.Value = groupid;
                this.HFClassID.Value = classid;
            }
        }

        //保存
        protected void TB_baocun_Click(object sender, EventArgs e)
        {
            if (this.IsYanzhen.Value != "true")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('存在不符合要求的数据！');</script>");
                return;
            }

            DataTable dt = Session["ExcelInfo"] as DataTable;
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder result = new StringBuilder("");
                string noraw = "";
                string error = "";
                //dt = this.ExcelToDataTable_Hebing(dt);//合并相同品号的数据
                foreach (DataRow dr in dt.Rows)
                {
                    string RawId = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + dr["InDBid"].ToString() + "'").Tables[0].Rows[0]["RawID"].ToString();
                    Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawId));
                    if (md_Raw == null || md_Raw.id <= 0)
                    {
                        noraw += dr["RAW"].ToString() + "(" + dr["InDBid"].ToString() + ")　";
                        continue;
                    }
                    Catering_Model.InDbInfo cmii = new Catering_Model.InDbInfo();
                    cmii.id = new Catering_Rules.InDbInfo().GetMaxId();
                    cmii.GroupID = Convert.ToInt32(dr["GroupID"]);
                    cmii.ClassID = Convert.ToInt32(dr["ClassID"]);
                    cmii.DBID = md_Raw.RAWTID;
                    cmii.RAWID = Convert.ToInt32(RawId);
                    cmii.RAWTID = md_Raw.RAWID;
                    cmii.RAWIDS = md_Raw.RAWIDS;
                    DateTime AddDate = DateTime.Now;
                    if (!string.IsNullOrEmpty(this.txt_addtime.Text))
                    {
                        DateTime.TryParse(this.txt_addtime.Text, out AddDate);
                    }
                    cmii.IntDate = AddDate;
                    cmii.PiaoDate = Convert.ToDateTime(dr["PiaoDate"]);
                    cmii.RAW = dr["RAW"].ToString();
                    cmii.Specifications = dr["Specifications"].ToString();
                    cmii.Number = dr["Number"].ToString();
                    cmii.CMP = dr["CMP"].ToString();
                    //cmii.AmountMoney = Convert.ToDecimal(dr["AmountMoney"].ToString());
                    //cmii.Weight = dr["Weight"].ToString();
                    cmii.Back = dr["Back"].ToString();
                    cmii.InDBid = dr["InDBid"].ToString();
                    cmii.Price = dr["Price"].ToString();

                    decimal sum = new View_Monitor().FormatDecimal(cmii.Number);//总重量
                    bool iskg = true;
                    decimal guige = 1;
                    decimal UtilKg = Toolss.GetSpecifications(Convert.ToInt32(cmii.RAWID), cmii.CMP, out iskg);
                    guige = iskg ? 1000 : 1;
                    decimal weight = Toolss.GetMathResult(UtilKg * sum, 2, 3);
                    cmii.Weight = weight.ToString();
                    cmii.SumNumber = weight * guige;

                    bool flag = new Catering_Rules.BalanceInfo().AddInDBInfo(Convert.ToInt32(RawId), Convert.ToInt32(dr["ClassID"]), cmii.InDBid, AddDate, cmii.Number, cmii.Price, cmii.id);
                    if (flag)
                    {
                        new Catering_Rules.InDbInfo().Add(cmii);
                    }
                    else
                    {
                        error += dr["RAW"].ToString() + "(" + dr["InDBid"].ToString() + ")　";
                    }
                }
                Session["ExcelInfo"] = null;
                if (!string.IsNullOrEmpty(noraw)) result.Append("原料不存在的数据：" + noraw);
                if (!string.IsNullOrEmpty(error)) result.Append("价格或数量为0的数据：" + error);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！" + result.ToString() + "');window.location='Rkgl.aspx';</script>");
            }
            else
            {
                View_Operaction_Common.Show(this, "没有数据保存");
            }

        }

        //结算单价
        private void Get_Out_Raw_jieyu(Int32 GroupID, Int32 ClassID, Int32 RawID, Double shuliang, Double jine, out Double jieyu, out Double zongjin)
        {
            Double Up_jieyu = 0;
            Double Up_danjias = 0;
            Get_OutRaw_Max_Row(GroupID, ClassID, RawID, out  Up_jieyu, out  Up_danjias);

            //出库结余+入库数量
            jieyu = Up_jieyu + shuliang;
            //出库总金额+入库金额
            zongjin = (Up_jieyu * Up_danjias + jine) / jieyu;

        }

        // 查询到最后一条记录
        private void Get_OutRaw_Max_Row(Int32 GroupID, Int32 ClassID, Int32 RawID, out Double jieyu, out Double zongjin)
        {
            Double jie = 0;
            Double zong = 0;
            DataSet ds = new Catering_Rules.InDbInfo().GetAllList();
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {

                    DataRow[] drs = ds.Tables[0].Select("GroupID=" + GroupID + " and ClassID=" + ClassID + "  and RAWID=" + RawID);

                    if (drs.Length > 0)
                    {
                        //结余
                        Double.TryParse(drs[drs.Length - 1]["temp1"] != null ? drs[drs.Length - 1]["temp1"].ToString() : "0", out jie);
                        Double.TryParse(drs[drs.Length - 1]["temp2"] != null ? drs[drs.Length - 1]["temp2"].ToString() : "0", out zong);

                    }
                    else
                    {
                        jie = 0;
                        zong = 0;
                    }

                }
            }
            jieyu = jie;
            zongjin = zong;
        }

        //导入Excel
        protected void BT_daoru_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.FileName != null && this.FileUpload1.FileName.Length > 0)
            {
                DataSet ds = View_Operaction_Excel.exceltodataset(dmo.UpFile(this.FileUpload1));
                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0] != null)
                    {
                        this.IsYanzhen.Value = "true";//验证数据是否全部符合要求
                        DataTable dt = ExcelToDataTable(ds.Tables[0], true);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            PagedDataSource objPage = new PagedDataSource();
                            DataTable newdt = this.ExcelToDataTable_Hebing(dt);//合并相同品号的数据
                            if (newdt.Rows.Count < (dt.Rows.Count / 2))
                            {
                                View_Operaction_Common.Show(this, "此文件数据已导入，请勿重复导入！");
                            }
                            else
                            {
                                dt = newdt;
                                Session["ExcelInfo"] = dt;
                                objPage.DataSource = dt.DefaultView;
                                //允许分页
                                objPage.AllowPaging = false;
                                Repeater1.DataSource = objPage;

                                //进行数据绑定
                                Repeater1.DataBind();
                                TB_baocun.Enabled = true;
                                //but_check.Enabled = true;
                            }
                        }
                    }
                }
            }
            else
            {
                View_Operaction_Common.Show(this, "请浏览文件");
            }

        }

        //读取Excel数据并验证
        private DataTable ExcelToDataTable(DataTable dt, Boolean Rest)
        {
            DataTable dttemp = new DataTable();
            DataTable dt_InDbInfo = new Catering_Rules.InDbInfo().GetList("1=2").Tables[0];
            dttemp = dt_InDbInfo.Clone();

            //string strPer = Session["UserID"] as string;
            //Catering_Model.Personnel Model_cmp = new Catering_Rules.Personnel().GetModel(Convert.ToInt32(strPer != null && strPer.Trim().Length > 0 ? strPer.Trim() : "1"));
            int ClassID = Convert.ToInt32(this.HFClassID.Value);

            int i = 1;
            foreach (DataRow dr_Temp in dt.Rows)
            {
                DataRow dr = dttemp.NewRow();
                if (dr_Temp != null && dr_Temp[0] != null && dr_Temp[0].ToString().Trim().Length > 0)
                {
                    //序号	工作区	工作台 	仓库	入库日期	单据日期	品号	品名	规格	库数量	单位 	单价 	重量	原料大类	原料细类	备注	temp1	temp2
                    Int32 AreaID = new Catering_Rules.ClassInfo().GetModel(ClassID).AreaID;
                    dr["id"] = i;
                    dr["GroupID"] = AreaID;
                    dr["ClassID"] = ClassID;
                    dr["DBID"] = 1;
                    dr["IntDate"] = DateTime.Now;
                    DateTime dtime = DateTime.Now;
                    DateTime.TryParse(dr_Temp[2].ToString(), out dtime);
                    dr["PiaoDate"] = dtime;
                    dr["RAWID"] = 1;
                    dr["RAW"] = dr_Temp[3];
                    dr["Specifications"] = dr_Temp[4];
                    dr["Number"] = dr_Temp[5];
                    //dr["CMP"] = dr_Temp[6].ToString() == "公斤" ? "kg" : dr_Temp[6];
                    //dr["AmountMoney"] = Convert.ToDecimal(dr_Temp[9]);
                    decimal temp9 = 0;
                    decimal.TryParse(dr_Temp[9].ToString(), out temp9);
                    dr["Weight"] = temp9;
                    dr["RAWTID"] = 1;
                    dr["RAWIDS"] = 1;
                    dr["Back"] = dr_Temp[1];
                    dr["temp1"] = "";//结余量
                    dr["temp2"] = "";//平均单价
                    dr["InDBid"] = dr_Temp[0];
                    dr["Price"] = dr_Temp[7];

                    if (dr_Temp[5] == null || string.IsNullOrEmpty(dr_Temp[5].ToString()) || Convert.ToDecimal(dr_Temp[5].ToString()) <= 0)
                    {
                        dr["Number"] = 0;
                        dr["Price"] = 0;
                        dr["CMP"] = "";
                    }
                    else if (dr_Temp[7] == null || string.IsNullOrEmpty(dr_Temp[7].ToString()) || Convert.ToDecimal(dr_Temp[7].ToString()) <= 0)
                    {
                        dr["Number"] = 0;
                        dr["Price"] = 0;
                        dr["CMP"] = "";
                    }
                    else
                    {
                        if (Rest)
                        {
                            string GroupID = new Catering_Rules.ClassInfo().GetModel(ClassID).AreaID.ToString();
                            dr["temp2"] = CheangerRaw(GroupID, ClassID.ToString(), "1", dr_Temp[0].ToString(), dr_Temp[5].ToString());
                        }
                        else
                        {
                            dr["temp2"] = "";
                        }

                        if (dr["temp2"].ToString() != "" && dr["temp2"].ToString() != "Yes_Set")
                        {
                            this.IsYanzhen.Value = "false";
                        }

                        #region 验证单位

                        if (dr["temp2"].ToString() == "")
                        {
                            DataTable dt_rma = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + dr["InDBid"].ToString() + "'").Tables[0];
                            for (int k = 0; k < dt_rma.Rows.Count; k++)
                            {
                                int RawId = Convert.ToInt32(dt_rma.Rows[k]["RawID"]);
                                if (RawId <= 0) continue;
                                Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(RawId);

                                if (md_Raw != null && !string.IsNullOrEmpty(md_Raw.temp2))
                                {
                                    decimal importprice = Convert.ToDecimal(dr_Temp[7]);
                                    decimal importNumber = Convert.ToDecimal(dr_Temp[5]);
                                    decimal turnNumber = 0;
                                    decimal turnPrice = 0;
                                    bool isTurnSuccessed = false;
                                    bool noTurn = false;
                                    string importUnit = dr_Temp[6].ToString() == "公斤" ? "kg" : dr_Temp[6].ToString();
                                    string unit = "";
                                    GetTurnUnitNumberAndPrice(md_Raw.id, Convert.ToInt32(md_Raw.temp2), importUnit, importNumber, importprice, out turnNumber, out turnPrice, out unit, out isTurnSuccessed, out noTurn);
                                    if (noTurn)
                                    {
                                        dr["Number"] = importNumber;
                                        dr["Price"] = importprice;
                                        dr["CMP"] = unit;
                                        break;
                                    }
                                    else if (isTurnSuccessed)//单位不一致
                                    {
                                        if (turnNumber <= 0 || turnPrice <= 0)
                                        {
                                            if (k < (dt_rma.Rows.Count - 1)) continue;
                                            dr["Number"] = importNumber;
                                            dr["Price"] = importprice;
                                            dr["temp2"] = "NO_Unit";
                                            dr["CMP"] = importUnit + "(" + unit + ")";
                                            this.IsYanzhen.Value = "false";
                                        }
                                        else
                                        {
                                            dr["Number"] = turnNumber;
                                            dr["Price"] = turnPrice;
                                            dr["temp2"] = "Turn_Unit";
                                            dr["CMP"] = unit;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        if (k < (dt_rma.Rows.Count - 1)) continue;
                                        dr["Number"] = importNumber;
                                        dr["Price"] = importprice;
                                        dr["temp2"] = "NO_Unit";
                                        dr["CMP"] = importUnit + "(" + unit + ")";
                                        this.IsYanzhen.Value = "false";
                                    }
                                }
                            }
                            dt_rma.Dispose();
                        }

                        #endregion
                    }
                    dttemp.Rows.Add(dr);
                    i++;
                }
            }
            return dttemp;
        }

        //将Excel数据信息合并
        private DataTable ExcelToDataTable_Hebing(DataTable dt)
        {
            DataTable dttemp = new DataTable();
            DataTable dt_InDbInfo = new Catering_Rules.InDbInfo().GetList("1=2").Tables[0];
            dttemp = dt_InDbInfo.Clone();
            StringBuilder result = new StringBuilder("");
            string noraw = "";
            string repeatraw = "";
            string haveraw = "";
            string norawi = "";
            int norawnum = 0;
            int repeatrawnum = 0;
            int haverawnum = 0;
            int norawinum = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                int i = 1;

                foreach (DataRow row in dt.Rows)
                {
                    string strwhere = "InDBid='" + row["InDBid"].ToString() + "'";
                    decimal tempnum = Convert.ToDecimal(row["Number"]);//入库数量
                    decimal temppice = Convert.ToDecimal(row["Price"]);//单价
                    if (tempnum <= 0 || temppice <= 0)
                    {
                        noraw += row["RAW"].ToString() + "(" + row["InDBid"].ToString() + ")　";
                        norawnum++;
                        continue;
                    }
                    else if (dttemp.Select(strwhere).Count() > 0)
                    {
                        decimal old_Number = Convert.ToDecimal(dttemp.Select(strwhere)[0]["Number"]);//入库数量
                        decimal old_danjia = Convert.ToDecimal(dttemp.Select(strwhere)[0]["Price"]);//单价
                        //decimal old_AmountMoney = Convert.ToDecimal(dttemp.Select(strwhere)[0]["AmountMoney"]);//总金额
                        decimal old_Weight = Convert.ToDecimal(dttemp.Select(strwhere)[0]["Weight"]);//重量

                        decimal Number = Convert.ToDecimal(row["Number"]);//入库数量
                        decimal danjia = Convert.ToDecimal(row["Price"]);//单价
                        //decimal AmountMoney = Convert.ToDecimal(row["AmountMoney"]);//总金额
                        decimal Weight = Convert.ToDecimal(row["Weight"]);//重量

                        dttemp.Select(strwhere)[0]["Number"] = (old_Number + Number).ToString();//新数量
                        //decimal New_AmountMoney = old_danjia * old_Number + danjia * Number;
                        //dttemp.Select(strwhere)[0]["AmountMoney"] = (New_AmountMoney).ToString();//新总金额
                        //dttemp.Select(strwhere)[0]["Price"] = (New_AmountMoney / (old_Number + Number)).ToString();//新单价
                        dttemp.Select(strwhere)[0]["Price"] = (old_danjia + danjia) / 2;
                        dttemp.Select(strwhere)[0]["Weight"] = (old_Weight + Weight).ToString();//新重量
                        repeatraw += row["RAW"].ToString() + "(" + row["InDBid"].ToString() + ")　";
                        repeatrawnum++;
                    }
                    else
                    {
                        string RawId = "";
                        try
                        {
                            RawId = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + row["InDBid"].ToString() + "'").Tables[0].Rows[0]["RawID"].ToString();
                        }
                        catch
                        {
                            RawId = "";
                        }
                        if (RawId == "")
                        {
                            row[0] = i;
                            dttemp.Rows.Add(row.ItemArray);
                            i++;
                        }
                        else
                        {
                            Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawId));
                            if (md_Raw == null || md_Raw.id <= 0)
                            {
                                norawi += row["RAW"].ToString() + "(" + row["InDBid"].ToString() + ")　";
                                norawinum++;
                            }
                            else
                            {
                                DateTime AddDate = DateTime.Now;
                                if (!string.IsNullOrEmpty(row["PiaoDate"].ToString())) DateTime.TryParse(row["PiaoDate"].ToString(), out AddDate);
                                DataTable fdt = new Catering_Rules.InDbInfo().GetList(" ClassID=" + row["ClassID"].ToString() + " AND Convert(decimal(18,2),Number)=Convert(decimal(18,2),'" + tempnum + "') AND RAWID=" + RawId + " AND  InDBid='" + row["InDBid"].ToString() + "' AND Year(PiaoDate)=" + AddDate.Year + " AND Month(PiaoDate)=" + AddDate.Month + " AND Day(PiaoDate)=" + AddDate.Day).Tables[0];
                                if (fdt != null && fdt.Rows.Count > 0)
                                {
                                    haveraw += row["RAW"].ToString() + "(" + row["InDBid"].ToString() + ")　";
                                    haverawnum++;
                                }
                                else
                                {
                                    //DataRow r = row.ItemArray;
                                    row[0] = i;
                                    dttemp.Rows.Add(row.ItemArray);
                                    i++;
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(noraw)) result.Append("价格或数量为0的数据(" + norawnum + ")：" + noraw + "<br/>");
            if (!string.IsNullOrEmpty(repeatraw)) result.Append("重复的数据(" + repeatrawnum + ")：" + repeatraw + "<br/>");
            if (!string.IsNullOrEmpty(norawi)) result.Append("品号原料不存在的数据(" + norawinum + ")：" + norawi + "<br/>");
            if (!string.IsNullOrEmpty(haveraw)) result.Append("已入库的数据(" + haverawnum + ")：" + haveraw + "<br/>");
            this.errordiv.InnerHtml = result.ToString();
            return dttemp;
        }

        //验证数据是否符合要求
        private string CheangerRaw(string strGroupID, string strClassID, string strDBID, string strRaw, string strNumber)
        {
            View_Operaction_Common voc = new View_Operaction_Common();
            string str = string.Empty;
            DataTable dt = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + strRaw + "'").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                string RawID = dt.Rows[0]["RawID"].ToString();
                Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawID));
                if (md_Raw != null)
                {
                    DataTable dt_RoomWaing = new Catering_Rules.RoomWaing().GetList("GroupID=" + strGroupID + " and ClassID=" + strClassID + " and RAWID=" + RawID).Tables[0];
                    if (dt_RoomWaing != null && dt_RoomWaing.Rows.Count > 0)
                    {
                        decimal d_MaxContent = Convert.ToDecimal(dt_RoomWaing.Rows[0]["MaxContent"].ToString());//库房警戒线
                        decimal d_jieyuliang;//库房结余量

                        ArrayList al = new Catering_Rules.BalanceInfo().GetLastBalanceInfo(strClassID, RawID, strRaw);
                        if (al != null && al.Count >= 1)
                        {
                            d_jieyuliang = Convert.ToDecimal(al[1]);
                        }
                        else
                        {
                            d_jieyuliang = 0;
                        }
                        //string strwhere = "GroupID=" + strGroupID + " and ClassID=" + strClassID + " and RAWID=" + RawID + " and InDBid='" + strRaw + "'";
                        //DataTable dt_InDbInfo = new Catering_Rules.InDbInfo().GetList(1, strwhere, " IntDate desc").Tables[0];
                        //if (dt_InDbInfo != null && dt_InDbInfo.Rows.Count > 0)
                        //{
                        //    d_jieyuliang = Convert.ToDecimal(dt_InDbInfo.Rows[0]["temp1"].ToString());
                        //}
                        //else
                        //{
                        //    d_jieyuliang = 0;
                        //}

                        if (d_MaxContent > (Convert.ToDecimal(strNumber) + Convert.ToDecimal(d_jieyuliang)))
                        {
                            str = "";//未超过警戒线
                        }
                        else
                        {
                            str = "Yes_Set";//超过警戒线
                        }
                    }
                    else
                    {
                        str = "";//无警戒线
                    }
                }
                else
                {
                    str = "NO_Raw";//无该品号
                }
            }
            else
            {
                str = "NO_Raw";//无该品号
            }
            return str;
        }

        //检查Excel
        protected void TB_Chenck_Click(object sender, EventArgs e)
        {

            DataTable dt_Excel = Session["ExcelInfo"] as DataTable;
            if (dt_Excel != null)
            {
                if (dt_Excel.Rows.Count > 0 && dt_Excel != null)
                {
                    PagedDataSource objPage = new PagedDataSource();

                    DataTable dt = ExcelToDataTable(dt_Excel, true);
                    objPage.DataSource = dt.DefaultView;
                    //允许分页
                    objPage.AllowPaging = false;
                    Repeater1.DataSource = objPage;

                    //进行数据绑定
                    Repeater1.DataBind();
                }
                else
                {
                    View_Operaction_Common.Show(this, "请导入数据");
                }
            }
            //this.but_hebing.Enabled = true;
        }

        //合并Excel
        protected void TB_hebing_Click(object sender, EventArgs e)
        {

            DataTable dt_Excel = Session["ExcelInfo"] as DataTable;
            if (dt_Excel != null)
            {
                if (dt_Excel.Rows.Count > 0 && dt_Excel != null)
                {
                    PagedDataSource objPage = new PagedDataSource();
                    DataTable dt_Hebing = new DataTable();
                    DataTable dt = ExcelToDataTable(dt_Excel, true);
                    dt_Hebing = ExcelToDataTable_Hebing(dt);
                    if (dt_Hebing == null || dt_Hebing.Rows.Count < 1)
                    {
                        View_Operaction_Common.Show(this, "没有符合数据");
                    }
                    else
                    {
                        Session["ExcelInfo_Hebing"] = dt_Hebing;

                    }
                    objPage.DataSource = dt_Hebing.DefaultView;
                    //允许分页
                    objPage.AllowPaging = false;
                    Repeater1.DataSource = objPage;

                    //进行数据绑定
                    Repeater1.DataBind();
                }
                else
                {
                    View_Operaction_Common.Show(this, "请导入数据");
                }
            }
        }

        //设置行颜色
        public string GetStyle(string strNumber)
        {
            string strBgC = string.Empty;
            switch (strNumber.Trim())
            {
                case "":
                    strBgC = "background-color: #f4fbff; height: 32px";
                    break;
                case "Yes_Set"://超过 警戒线 
                    strBgC = "background-color:#7F7F00; height: 32px";
                    break;
                case "NO_Raw"://没有原料 
                    strBgC = "background-color:red; height: 32px";
                    break;
                case "NO_Unit"://单位错误
                    strBgC = "background-color:#AABFAA; height: 32px";
                    break;
                case "Turn_Unit"://单位智能转换
                    strBgC = "background-color:#96E23F; height: 32px";
                    break;
            }
            return strBgC;
        }

        protected void lb_rest_Click(object sender, EventArgs e)
        {
            Session["ExcelInfo"] = null;
        }

        /// <summary>
        /// 获取转换后的数量和单位
        /// </summary>
        /// <param name="rawid">原料ID</param>
        /// <param name="unitID">原料单位</param>
        /// <param name="importUnit">导入的单位</param>
        /// <param name="importNumber">导入的数量</param>
        /// <param name="importPrice">导入的价格</param>
        /// <param name="turnNumber">转换后的数量</param>
        /// <param name="turnPrice">转换后的价格</param>
        /// <param name="isTurnSuccessed">智能转换是否成功</param>
        /// <param name="noTurn">是否需要进行智能转换</param>
        public void GetTurnUnitNumberAndPrice(int rawid, int unitID, string importUnit, decimal importNumber, decimal importPrice, out decimal turnNumber, out decimal turnPrice, out string turnUnit, out bool isTurnSuccessed, out bool noTurn)
        {
            //初始化
            isTurnSuccessed = false;
            turnNumber = 0;
            turnPrice = 0;
            noTurn = false;
            turnUnit = importUnit;
            Catering_Model.Units unit = new Catering_Rules.Units().GetModel(unitID);

            if (importPrice == Convert.ToDecimal(1.078))
            {

            }

            if (unit != null && unit.UName != importUnit)//单位不一致
            {
                //对单位进行智能转换
                DataTable dt_RMUnit = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(rawid).Tables[0];
                turnUnit = unit.UName;
                Dictionary<string, decimal> danweiguige = new Dictionary<string, decimal>();
                List<string> danweiguigeName = new List<string>();
                int unitIndex = 0;
                int importUnitIndex = 0;

                if (dt_RMUnit != null && dt_RMUnit.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_RMUnit.Rows.Count; i++)
                    {
                        decimal tempnum = Convert.ToDecimal(dt_RMUnit.Rows[i]["Number"]);
                        string danwei = dt_RMUnit.Rows[i]["UName"].ToString();
                        if (!danweiguigeName.Contains(danwei))
                        {
                            danweiguige.Add(danwei, tempnum);
                            danweiguigeName.Add(danwei);
                            if (danwei == importUnit) importUnitIndex = (danweiguigeName.Count - 1);
                            if (danwei == unit.UName) unitIndex = (danweiguigeName.Count - 1);
                        }
                    }
                    dt_RMUnit.Dispose();
                }
                decimal jisuan = 1;
                if (danweiguigeName.Contains(importUnit))//原料规格中有导入的单位
                {
                    if (unitIndex > importUnitIndex)
                    {
                        for (int i = (importUnitIndex + 1); i <= unitIndex; i++)
                        {
                            jisuan = jisuan * danweiguige[danweiguigeName[i]];
                        }
                        turnNumber = importNumber * jisuan;
                        turnPrice = Toolss.GetMathResult(importPrice / jisuan, 2, 3);
                        isTurnSuccessed = true;
                        turnUnit = unit.UName;
                    }
                    else if (unitIndex < importUnitIndex)
                    {
                        for (int i = importUnitIndex; i > unitIndex; i--)
                        {
                            jisuan = jisuan * danweiguige[danweiguigeName[i]];
                        }
                        turnNumber = Toolss.GetMathResult(importNumber / jisuan, 2, 3);
                        turnPrice = importPrice * jisuan;
                        isTurnSuccessed = true;
                        turnUnit = unit.UName;
                    }
                }
            }
            else
            {
                noTurn = true;
            }
        }
    }
}